package grimbo.goodwinfooty.processing;

import grimbo.goodwinfooty.xls.XLS2CSV;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Map;

public class XLS2CSVProcessor implements Processor {
    public final static String CTX_CSV_BYTES = "csvBytes";

    public String process(Map context) throws Exception {
        InputStream in = (InputStream) context.get(XLS2InputStreamProcessor.CTX_XLS_INPUT_STREAM);
        byte[] csvBytes = convertXLS2CSV(in);
        context.put(CTX_CSV_BYTES, csvBytes);
        return null;
    }

    private byte[] convertXLS2CSV(InputStream in) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);

        XLS2CSV xls2csv = new XLS2CSV(in, ps);
        xls2csv.process();
        ps.flush();
        return baos.toByteArray();
    }
}
